package com.net.xpay.core.helper;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.common.exception.BusinessException;
import com.net.xpay.core.CoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.time.LocalDateTime;

@Slf4j
@Component
public class AliyunUploaderHelper {

    @Autowired
    private CoreProperties coreProperties;

    private OSS ossClient;

    private synchronized void initClient() {
        if (ossClient != null) {
            return;
        }
        // 创建OSSClient实例。
        String endpoint = "https://" + coreProperties.getOssRegion();

        ossClient = new OSSClientBuilder().build(endpoint, coreProperties.getOssAccessKey(), coreProperties.getOssSecretKey());
    }

    public String upload(String fileName, InputStream inputStream, LocalDateTime expiration) {
        if (ossClient == null) {
            initClient();
        }
        // 填写Bucket名称，例如examplebucket。
        String bucketName = coreProperties.getOssUploadDir();
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "common/" + fileName;
        // 公网地址
        String endpoint = coreProperties.getOssRegion().replace("-internal", "");

        try {
            ossClient.putObject(bucketName, objectName, inputStream);
            return "https://" + bucketName + "." + endpoint +  "/" + objectName;
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "上传失败");
        } catch (ClientException ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:" + ce.getMessage());
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "上传失败");
        }

    }

}
